﻿package com.cilico.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.widget.LinearLayout;

import com.cilico.ConfigManager;
import com.cilico.Mid;
import com.cilico.R;
import com.cilico.citylist.AGPS;
import com.cilico.citylist.CityListActivity;
import com.cilico.utils.PackageManagerAndroid;
import com.cilico.utils.Utils;

/**
 * 程序入口
 * @author lv.xiangan
 *
 */
public class SplashScreen extends BaseView {
	private Timer timer_; // 延时初始化
	public Bitmap logoOn_;
	static boolean gotoStart_ = false; // 当显示guidebook后为true
	final static int START_RED = 0x0f;
	final static int START_GREEN = 0x36;
	final static int START_BLUE = 0x6a;
	final static int END_RED = 0x05;
	final static int END_GREEN = 0x5d;
	final static int END_BLUE = 0xb7;
	int bgColor_ = 0x00055db7;
	private String errmsg_; // 初始化异常捕捉
	PackageManagerAndroid pm_ = null; // 数据库对象
	SplashScreenBackgroundView splashBG; // 闪屏背景视图
	String versionName; // 软件版本号，存放的是Manifest文件android:versionName属性值
	/**是不是已经弹出了设置页面*/
	static boolean haveSetNet_ = false;
	/**标识是从城市列表跳转的*/
	public static boolean IS_GUIDEBOOK = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ConfigManager.currentView_ = this;
		hideSystemBar(this);
		Utils.init(this);
		Utils.calculateScreenSize(this);
	    activities_ = new ArrayList<Activity>();

	    // 开启agps定位
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				Mid.agps_ = new AGPS();
				Mid.agps_.start();
			}
		});
		
	    // 读取本地数据库，判断是否第一次使用
		String notFirstUse = null;
		try {
			pm_ = new PackageManagerAndroid(this);
			String save = pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.SAVEPROPERTY_DB);
			if (save != null) {
				Mid.saveProperty_ = Utils.getSavePropoerty(save);
				if (null != Mid.saveProperty_) {
					Object o = Mid.saveProperty_.get("NOT_FIRST_USE");
					Object o2 = Mid.saveProperty_.get("current_city");
					if (o != null)
						notFirstUse = (String) o;
					if (o2 != null)
						CityListActivity.dbCityName_ = (String) o2;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 读取软件版本号
		PackageManager pm = this.getPackageManager();
		PackageInfo pi = null;
		try {
			pi = pm.getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		if (pi != null) {
			versionName = pi.versionName;
		}

		// 非首次运行，直接进入闪屏界面
		if (notFirstUse != null && notFirstUse.equals(versionName)) {
			start();
		} else {// 该版本手机银行安装后第一次运行
			if (Mid.saveProperty_ == null) {
				Mid.saveProperty_ = new HashMap<String, Object>();
			}
//			Bundle data = new Bundle();
//			if (Mid.saveProperty_.isEmpty()) { // 之前从未安装过手机银行
//				data.putBoolean("key", false);
//				Intent intent = new Intent();
//				intent.setClass(SplashScreen.this, GuideBook.class);
//				intent.putExtras(data);
//				startActivity(intent);
//			} else { // 之前安装过手机银行
//				start();
//			}
			start();
			Mid.saveProperty_.put("NOT_FIRST_USE", versionName);
		}
		
		// 获取设备信息，用于握手时向后台传送
		TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); // 获取devicetoken
		ConfigManager.DEVICETOKEN = tm.getDeviceId();
		//获取IMSI和sim卡序列号、MAC address
		String imsi = tm.getSubscriberId();
		String simNumber = tm.getSimSerialNumber(); 
		WifiManager wifi = (WifiManager) this.getBaseContext().getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		String address = info.getMacAddress();
		//'I'后面拼接的是imsi号；'S'后面拼接的是sim卡序列号； 'M'后面拼接的是mac地址
		if (ConfigManager.DEVICETOKEN!=null) {
			if (null != imsi && !imsi.trim().equals("")) {
				ConfigManager.DEVICETOKEN.concat("'I'").concat(imsi.trim());
			}else if(null != simNumber && !simNumber.trim().equals("")){
				ConfigManager.DEVICETOKEN.concat("'S'").concat(simNumber.trim());
			}else if(null != address && !address.trim().equals("")){
				ConfigManager.DEVICETOKEN.concat("'M'").concat(address.trim());
			}
		}
		//获取系统固件版本号
		ConfigManager.SYSTEMVISION = Utils.getSystemVersion();
	}


	private void start() {
		//先进入设置界面
		Bundle bundle = new Bundle();
		bundle.putBoolean("start", true);
		Intent intent = new Intent();
		intent.setClass(SplashScreen.this, SysSeting.class);
		intent.putExtras(bundle);
		startActivity(intent);
	}
	
	/**
	 * 闪屏界面
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2014-1-15下午3:44:01
	 */
	private void splash(){
		if (null != pm_)
			saveProperties(pm_);
		// 闪屏界面
		LinearLayout lls = new LinearLayout(this);
		lls.setBackgroundResource(R.drawable.loading);
		splashBG = new SplashScreenBackgroundView(this);
		lls.addView(splashBG);
		setContentView(lls);

		// 为保证闪屏效果，延时初始化
		timer_ = new Timer();
		timer_.schedule(new TimerTask() {
			public void run() {
				init();
			}
		}, 600);
	}

	protected void onRestart() {
		super.onRestart();
		if (gotoStart_ && haveSetNet_) {
//			start();
			splash();
		} else {
			finish();
		}

	}

	void init() {
		errmsg_ = null;
		try {
			mid_ = new Mid(this);
			mid_.pm_ = pm_;
			mid_.initApp(this);
		} catch (Exception ex) {
			errmsg_ = ex.getMessage();
			if (errmsg_ == null) {
				errmsg_ = "Initialization failed.";
			}
		}
		// 根据初始化的结果，主动发起ClientHello请求
		if (errmsg_ == null) {
			// 初始化成功
			mid_.handleLoginSuccess(this);
		} else {
			// 初始化失败或"badcookies"（未登陆）
			mid_.handleLoginFailure(this, errmsg_);
		}
	}

	public void setErrMsg(String msg) {
		errmsg_ = msg;
	}

	private void saveProperties(PackageManagerAndroid pm) {
		// 遍历哈西map，将其内容转化成字符串进行存储
		if (Mid.saveProperty_.size() > 0) {
			Iterator<Entry<String, Object>> iter = Mid.saveProperty_.entrySet().iterator();
			Map.Entry<String, Object> enter;
			String key, value;
			StringBuffer sb = new StringBuffer();
			if (null != iter) {
				while (iter.hasNext()) {
					// 将存储字符串按一定规则拼起
					enter = iter.next();
					key = enter.getKey().toString();
					value = enter.getValue().toString();
					if (!key.equals("") && !value.equals("")) {
						sb.append(key);
						sb.append(ConfigManager.SAVENEND);
						sb.append(value);
						sb.append(ConfigManager.SAVEVEND);
					}
				}
				pm.SAVEPROPERTYDB_.save(PackageManagerAndroid.SAVEPROPERTY_DB, sb.toString());
			}
		} else {
			pm.SAVEPROPERTYDB_.save(PackageManagerAndroid.SAVEPROPERTY_DB, "");
		}
	}

	/**
	 * 在开始读取界面按返回键，直接退出程序
	 * */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			exitApplication();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (IS_GUIDEBOOK) {
			start();
			IS_GUIDEBOOK = false;
		}
	}
}
